<template>
  <div class="basic-info-section">
    <h3 class="section-title">基本信息</h3>
    <el-divider />
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="formData.courseId" placeholder="请选择课程" style="width: 100%" :disabled="isReadonly">
            <el-option v-for="course in courses" :key="course.id" :label="course.name" :value="course.id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="学期" prop="termId">
          <el-select v-model="formData.termId" placeholder="请选择学期" style="width: 100%" :disabled="isReadonly">
            <el-option v-for="term in terms" :key="term.id" :label="term.name" :value="term.id" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="专业">
          <el-input 
            :value="currentCourseInfo.majorNames" 
            disabled 
            style="width: 100%" 
            placeholder="请先选择课程"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="培养层次">
          <el-input 
            :value="currentCourseInfo.cengCiNames" 
            disabled 
            style="width: 100%" 
            placeholder="请先选择课程"
          />
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="开课单位" prop="departmentIds">
          <el-select v-model="formData.departmentIds" multiple placeholder="请选择开课单位" style="width: 100%" :disabled="isReadonly">
            <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="课程类型">
          <el-input 
            :value="currentCourseInfo.courseTypeName" 
            disabled 
            style="width: 100%" 
            placeholder="请先选择课程"
          />
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="课时">
          <el-input 
            :value="currentCourseInfo.totalHours" 
            disabled 
            style="width: 100%" 
            placeholder="请先选择课程"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="考核类型">
          <el-input 
            :value="currentCourseInfo.examineTypeName" 
            disabled 
            style="width: 100%" 
            placeholder="请先选择课程"
          />
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="使用教材" prop="textbook">
          <el-input v-model="formData.textbook" placeholder="请输入使用教材" :disabled="isReadonly" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="教材类别" prop="textbookType">
          <el-select v-model="formData.textbookType" placeholder="请选择教材类别" style="width: 100%" :disabled="isReadonly">
            <el-option label="统编教材" value="1" />
            <el-option label="自编教材" value="2" />
            <el-option label="其他教材" value="3" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    
    <!-- 教学任务选择器组件放在最后 -->
    <el-divider />
    <TeachingMissionSelector
      v-if="formData.courseId && formData.termId"
      :current-mission-id="currentMissionId"
      :course-id="formData.courseId"
      :term-id="formData.termId"
      :selected-missions="selectedMissions"
      :is-readonly="isReadonly"
      @update:selectedMissions="updateSelectedMissions"
      @change="onMissionSelectionChange"
    />
  </div>
</template>

<script>
import { computed, ref, watch } from 'vue';
import TeachingMissionSelector from './TeachingMissionSelector.vue';

export default {
  name: 'SummaryBasicInfo',
  components: {
    TeachingMissionSelector
  },
  props: {
    modelValue: {
      type: Object,
      required: true
    },
    courses: {
      type: Array,
      default: () => []
    },
    terms: {
      type: Array,
      default: () => []
    },
    teachingMissions: {
      type: Array,
      default: () => []
    },
    departments: {
      type: Array,
      default: () => []
    },
    isReadonly: {
      type: Boolean,
      default: false
    },
    currentMissionId: {
      type: [String, Number],
      default: null
    }
  },
  emits: ['update:modelValue', 'missions-changed'],
  setup(props, { emit }) {
    const formData = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    });

    const selectedMissions = ref([]);

    // 计算当前选中课程的相关信息（只读显示）
    const currentCourseInfo = computed(() => {
      const course = props.courses.find(c => c.id === formData.value.courseId);
      if (!course) {
        return {
          majorNames: '',
          cengCiNames: '',
          courseTypeName: '',
          examineTypeName: '',
          totalHours: ''
        };
      }
      
      return {
        majorNames: course.majorNames ? course.majorNames.join(', ') : '',
        cengCiNames: course.cengCiNames ? course.cengCiNames.join(', ') : '',
        courseTypeName: course.courseTypeName || '',
        examineTypeName: course.examineTypeName || '',
        totalHours: course.totalHours ? `${course.totalHours}学时` : ''
      };
    });

    // 更新选中的教学任务
    const updateSelectedMissions = (missions) => {
      selectedMissions.value = missions;
      // 更新表单数据中的教学任务ID
      const missionIds = missions.map(mission => mission.id);
      const updatedFormData = {
        ...formData.value,
        teachingMissionIds: missionIds
      };
      emit('update:modelValue', updatedFormData);
    };

    // 教学任务选择变化回调
    const onMissionSelectionChange = (missions) => {
      emit('missions-changed', missions);
    };

    // 初始化选中的教学任务
    watch(() => props.modelValue.teachingMissionIds, (newIds) => {
      if (newIds && Array.isArray(newIds) && props.teachingMissions.length > 0) {
        selectedMissions.value = props.teachingMissions.filter(mission => 
          newIds.includes(mission.id)
        );
      }
    }, { immediate: true });

    // 安全获取教学任务标签的方法（保留以防其他地方需要）
    const getTeachingMissionLabel = (tm) => {
      if (!tm) return '未知教学任务';
      
      // 优先使用 courseName 字段，然后尝试 course.name，最后使用默认值
      const courseName = tm.courseName || (tm.course && tm.course.name) || '未知课程';
      
      // 获取教师名称
      let teacherNames = '';
      if (tm.teacherNames && Array.isArray(tm.teacherNames)) {
        teacherNames = tm.teacherNames.join(',');
      } else if (tm.teachers && Array.isArray(tm.teachers)) {
        teacherNames = tm.teachers.map(t => t.name || '未知教师').join(',');
      } else {
        teacherNames = '未分配教师';
      }
      
      return `${courseName} - ${teacherNames}`;
    };

    return {
      formData,
      selectedMissions,
      currentCourseInfo,
      updateSelectedMissions,
      onMissionSelectionChange,
      getTeachingMissionLabel
    };
  }
};
</script>

<style scoped>
/* 基本信息区域样式 */
.basic-info-section {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  border: 1px solid #e9ecef;
}

.basic-info-section .section-title {
  color: #495057;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.basic-info-section .subsection-title {
  color: #6c757d;
  font-size: 14px;
  font-weight: 500;
  margin: 0 0 15px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-divider) {
  margin: 15px 0;
}

:deep(.el-input__inner) {
  text-align: left;
}

/* 只读输入框样式 */
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #fafafa;
  border-color: #e0e0e0;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .basic-info-section {
    padding: 15px;
  }
}
</style>